/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosn.coffeemaker.ant;

import java.io.File;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;

/**
 * An Ant class to build, run and test generated projects
 * 
 * @author selkhateeb
 */
public class Ant
{

    /**
     * Builds the java application by running the default tag.
     * Pre: build.xml file is configured with default tag.
     * Post: The application is built and ready for deployment.
     * @param antBuildXmlFile the path to the build.xml file.
     */
    public static void Build(String antBuildXmlFile)
    {
        RunAnt(antBuildXmlFile, "default");

    }

    /**
     * Runs "ant run"
     * Pre: 'run' task is defined in the ant build xml file.
     * Post: the application has started.
     * @param antBuildXmlFile
     */
    public static void Run(String antBuildXmlFile)
    {
        RunAnt(antBuildXmlFile, "run");
    }

    /**
     * Runs "ant test" <br />
     * Pre: "test" task is defined in the and build xml file.<br />
     * Post: the test classes have run and error/success message has been
     *       displayed.
     */
    public static void Test(String antBuildXmlFile)
    {
        RunAnt(antBuildXmlFile, "test");
    }

    /**
     * Runs the provided ant task for the specified ant build file
     * @param antBuildXmlFile
     * @param targetToExecute
     */
    private static void RunAnt(String antBuildXmlFile, String targetToExecute)
    {
        File buildFile = new File(antBuildXmlFile);
        Project p = new Project();
        p.setUserProperty("ant.file", buildFile.getAbsolutePath());
        DefaultLogger consoleLogger = new DefaultLogger();
        consoleLogger.setErrorPrintStream(System.err);
        consoleLogger.setOutputPrintStream(System.out);
        consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
        p.addBuildListener(consoleLogger);
        try
        {
            p.fireBuildStarted();
            p.init();
            ProjectHelper helper = ProjectHelper.getProjectHelper();
            p.addReference("ant.projectHelper", helper);
            helper.parse(p, buildFile);
            if (targetToExecute.equals("default"))
            {
                p.executeTarget(p.getDefaultTarget());
            }
            else
            {
                p.executeTarget(targetToExecute);
            }
            p.fireBuildFinished(null);
        }
        catch (BuildException e)
        {
            p.fireBuildFinished(e);
        }
    }
}
